package edu.nf.vrs.reservation.service;

import cn.hutool.core.bean.BeanUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.client.Channel;
import edu.nf.reservation.dto.ReservationDTO;
import edu.nf.reservation.exception.ReservationException;
import edu.nf.vrs.reservation.config.RabbitConfig;

import edu.nf.vrs.reservation.entity.Reservation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author Lv
 * @date 2022/3/30
 */
@Service
@Slf4j

public class ReserveConsumerService {

//    @DubboReference(interfaceClass = ReservationService.class,version = "1.0.0",check = false)
//    private ReservationService reservationService;

    @Autowired
    private ReservePersistService persistService;

    /**
     * 向消息队列发送消息
     * @param json 返回的json格式数据
     * @param headers 请求头
     * @param channel
     */
    @RabbitListener(queues = RabbitConfig.QUEUE_NAME)
    public void receiveMessage(@Payload String json,
                               @Headers Map<String,Object> headers,
                               Channel channel){
        try {
            //获取预约记录
            ReservationDTO reservationDTO = new ObjectMapper().readValue(json,ReservationDTO.class);
            //设置预约状态为有效的
            reservationDTO.setStatus(1);
            //将DTO的json数据复制到预约信息
            Reservation reservation = BeanUtil.copyProperties(reservationDTO, Reservation.class);
            //生成预约记录
            persistService.saveReservation(reservation);
            System.out.println("================》 异步消费mq预约记录");
        } catch (Exception e) {
            throw new ReservationException("预约失败！",e);
        }
    }
}
